
L.SessionList = L.Class.extend({
  includes: L.Mixin.Events,
  
  initialize: function(){
    this._sessionListId = "sessions";
    this._sessions = [];
    this._sendToServer = true;
//    this.useAdapter(L.clientAdapter);
  },

  sendToServer: function(bool){
    this._sendToServer = bool;
  },

  addSession: function(id, name){
    var session = {
      id:id,
      name:name
    };

    this._sessions.push(session);

    if(this._sendToServer){
      this.sendEvent({
          operation: "addSession",
          id: id,
          name: name
      });
    }

    this.fire('addSession', session);
  
  },

  eachSession: function(fn, context){
    var sessions = this._sessions;
    for(var key in sessions){
      if(sessions.hasOwnProperty(key)){
        fn.call(context, sessions[key]);
      }
    }
  },

  containsSessionId: function(id){
    return this._sessions.hasOwnProperty(id);
  },
  
  getSession: function(id){
    return this._sessions[id];
  },

  useAdapter: function(clientAdapter){
      var self = this;
      var sessionListId = this._sessionListId;

      var handler = new Handler(clientAdapter, {
        objectId: sessionListId,
        type: "EVENT",
        echo: false,
        receiveEvent: function(object, c){
          self.sendToServer(false);
          switch(c.operation){
            case "addSession":
              self.addSession(c.id, c.name);
              break;
            default:
              console.log("[WARNING] User.useAdapter: operacion no soportada: " + c.operation);
          }
          self.sendToServer(true);
        },
        setState: function(object, content){
          this._sessions = content;
        }
      });

      this.sendEvent = function(content){
        handler.sendEvent(sessionListId, content);  
      }
      
      clientAdapter.couple(sessionListId, handler);

  },


});
